import { Spin } from 'antd';
import React, { useState } from 'react';
import styles from './styles.less';
import uploadFile from '@/service/upload';
import { Editor } from '@tinymce/tinymce-react';

type IProps = {
  value?: string;
  height?: number;
  onChange?: (value: string) => void;
}

const apiKey = 'mttkawz714e9ejlq775winby6b0dyt073lfpy0h2qnpcm2em';

const EditorPro: React.FC<IProps> = props => {
  const { value, onChange, height = 500 } = props;
  const [loading, setLoading] = useState<boolean>(true);

  const init = {
    height,
    menubar: false,
    language: 'zh_CN',
    plugins: [
      'advlist autolink lists link image',
      'charmap print preview anchor help',
      'searchreplace visualblocks code',
      'insertdatetime media table paste wordcount',
    ],
    toolbar:
      'undo redo | formatselect | image | bold italic | \
      alignleft aligncenter alignright | \
      bullist numlist outdent indent | help',
    images_upload_handler: async (blobInfo:any, success:any, failure:any) => {
      const formData = new FormData();
      formData.append('imgfile', blobInfo.blob());
      try {
        const url = await uploadFile(formData);
        success(url);
      } catch (e) {
        failure('图片上传失败，请检查网络！');
      }
    },
  };

  return (
    <Spin
      tip="努力加载中"
      spinning={loading}
    >
      <div
        style={{ height: loading ? height : 'auto' }}
        className={loading ? styles.editor_wrapper : ''}
      >
        <Editor
          init={init}
          value={value}
          apiKey={apiKey}
          onEditorChange={onChange}
          scriptLoading={{ async: true }}
          onInit={() => setLoading(false)}
        />
      </div>
    </Spin>
  );
};


export default EditorPro;
